﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Business.Solr {
    //[Serializable]
    public class SolrQuery {
        public string Q { get; set; }

        /// <summary>
        /// inStock desc, price asc
        /// </summary>
        public string Sort { get; set; }

        public int Start { get; set; }

        public int Rows { get; set; }

        /// <summary>
        /// 过滤器
        /// </summary>
        public IList<string> Fq { get; private set; }

        /// <summary>
        /// 返回的字段，默认*全部字段
        /// <example>
        /// id,name,price
        /// id name price
        /// *
        /// </example>
        /// </summary>
        public IEnumerable<string> ReturnFields { get; set; }

        /// <summary>
        /// 分组统计
        /// </summary>
        public SolrQueryFacet Facet { get; set; }

        public SolrQueryHighlighting Highlighting { get; set; }

        public SolrQuery() {
            Fq = new List<string>();
        }

        public SolrQuery AddFq(string field, string value) {
            Fq.Add(string.Format("{0}:{1}", field, HttpUtility.UrlEncode(value)));
            return this;
        }

        public SolrQuery AddFq(IDictionary<string, string> dict) {
            foreach (var kvp in dict) {
                AddFq(kvp.Key, kvp.Value);
            }
            return this;
        }

        public IEnumerable<string> BuildUrlParameters() {
            if (!string.IsNullOrEmpty(Q))
                yield return string.Format("q={0}", Q);

            if (!string.IsNullOrEmpty(Sort))
                yield return string.Format("sort={0}", Sort);

            if (Start > 0)
                yield return string.Format("start={0}", Start);

            if (Rows >= 0)
                yield return string.Format("rows={0}", Rows);

            if (Fq != null) {
                foreach (var _ in Fq)
                    yield return string.Format("fq={0}", _);
            }

            if (ReturnFields != null)
                yield return string.Format("fl={0}", string.Join(",", ReturnFields));

            if (Facet != null) {
                foreach (var _ in Facet.BuildUrlParameters())
                    yield return _;
            }

            if (Highlighting != null) {
                foreach (var _ in Highlighting.BuildUrlParameters())
                    yield return _;
            }
        }
    }
}